package com.share.simple.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jose.jwk.OctetSequenceKey;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:caifan
 * @since 2023/7/13
 */
public class JwtUtil {

    private static String KEY = "MZ91FWIvlckTjJlM3FC8nt2awqPtqMXR";

    private static Long EXPIRE_TIME = 2 * 3600 * 1000L;

    /**
     * 生成token
     * @param claim
     * @return
     * @throws JOSEException
     */
    public static String generateToken(Map<String, Object> claim) {
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
        claim.put("expireTime", System.currentTimeMillis() + EXPIRE_TIME);
        Payload payload = new Payload(claim);
        JWSObject jwsObject = new JWSObject(header, payload);
        try {
            JWSSigner signer = new MACSigner(KEY);
            jwsObject.sign(signer);
        } catch (JOSEException e) {
            System.out.println(e.getMessage());
        }

        return jwsObject.serialize();
    }

    public static Long parseIdByToken(String token) throws ParseException{
        JWSObject jwsObject = JWSObject.parse(token);
        Map<String, Object> map = jwsObject.getPayload().toJSONObject();
        return (Long)map.get("id");
    }

    /**
     * token校验
     * @param token token
     * @return
     * @throws ParseException 解析异常
     * @throws JOSEException jos异常
     */
    public static Boolean verifyToken(String token) {
        try {
            JWSObject jwsObject = JWSObject.parse(token);
            JWSVerifier verifier = new MACVerifier(KEY);
            return jwsObject.verify(verifier);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        /*Map<String, Object> map = new HashMap<>();
        map.put("username", "admin");
        map.put("password", "123456");
        System.out.println(generateToken(map));*/
        System.out.println(verifyToken("eyJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cGlyZVRpbWUiOjE2ODkzOTMwOTM4MzYsInVzZXJuYW1lIjoiYWRtaW4ifQ.KeOyiarAZKcjL-em0V8CqGon1aLxrFzGF49b3CKtg7Y"));
        JWSObject jwsObject = JWSObject.parse("eyJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cGlyZVRpbWUiOjE2ODkzOTMwOTM4MzYsInVzZXJuYW1lIjoiYWRtaW4ifQ.KeOyiarAZKcjL-em0V8CqGon1aLxrFzGF49b3CKtg7Y");
        Map<String, Object> map = jwsObject.getPayload().toJSONObject();
        System.out.println(map.size());

    }

}
